const {User} = require('../../model/user');
const bcrypt = require('bcrypt');

module.exports = async(req, res, next) => {
    // 接收用户请求参数
    const {
        username,
        email,
        role,
        state,
        password
    } = req.body;
    // 即将要修改的用户ID
    const id = req.query.id;
    let userdata = await User.findOne({
        _id: id
    });
    const isValid = await bcrypt.compare(password, userdata.password);

    if (isValid) {
        // 更新用户信息
        await User.updateOne({
            _id: id
        }, {
            username: username,
            email: email,
            role: role,
            state: state

        
        });

        res.redirect('/admin/user');
    } else {
        // 比对失败
        let obj = {
            path: '/admin/user-edit',
            id: id,
            message: '密码比对失败'
        }
        next(JSON.stringify(obj));
    }

}